import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:path/path.dart';
import 'package:qgchat/common/class/queue/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/chatModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:sqflite/sqflite.dart';

import 'settings.dart';

class Db {
  /// 数据库
  Database db;

  /// 队列
  MyQueue queue = MyQueue();

  /// 用户信息
  UserInfoModel _userInfo;

  Db(this._userInfo);

  /// 开启数据库，创建消息表
  Future openDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, '$DATABASES_NAME');
    db = await openDatabase(
      path,
      version: 1,
      onCreate: (Database db, int version) async {
        await db.execute('''
        CREATE TABLE IF NOT EXISTS $MESSAGE_TABLE_NAME (
          id INTEGER PRIMARY KEY NOT NULL,
          token VARCHAR(50),
          userToken VARCHAR(50),
          message VARCHAR(255) NOT NULL,
          type INT(1) NOT NULL DEFAULT '1',
          userName VARCHAR(32) DEFAULT '未命名',
          userHead VARCHAR(50) DEFAULT '',
          isread INT(1) DEFAULT '0',
          createtime INT(10) NOT NULL,
          label VARCHAR(10) DEFAULT ''
        )
        ''');
      },
    );
  }

  /// 查询所有(包括非自己的私聊记录，测试用)
  queryAll() async {
    var msg = await db.query('$MESSAGE_TABLE_NAME');
    return msg;
  }

  /// 清空数据(测试用，慎用)
  clear() async {
    await db.delete('$MESSAGE_TABLE_NAME');
  }

  /// 插入私聊记录
  insert(Msglist values) async {
    if (values.message == null || values.message.length <= 0) return;
    await db.insert('$MESSAGE_TABLE_NAME', values.toJson());
    // Future Function() action = () async {
    //   await db.insert('$MESSAGE_TABLE_NAME', values.toJson());
    // };
    // queue.push(action);
  }

  /// 查询本人所有私聊记录
  Future queryMyAll({ctx}) async {
    if (ctx == null) {
      ctx = Global.context;
    }
    SocketState socketState = (state(ctx, 'socket') as SocketState);

    // 查询
    List<Map> list = await db.query(
      '$MESSAGE_TABLE_NAME',
      where: 'userToken = ?',
      whereArgs: [_userInfo.memberToken],
      groupBy: 'token',
      orderBy: 'createtime DESC',
    );

    // 转化为model
    List<ChatModel> chatlist = list.map((item) {
      Map<String, dynamic> chat = {
        "token": item['token'],
        "userName": item['userName'],
        "userHead": item['userHead'],
        "msglist": [item],
      };
      return ChatModel.fromJson(chat);
    }).toList();

    // 查询未读数
    chatlist.forEach((item) async {
      item.readCount = await queryNotReadCount(item.token);
    });

    // 初始化私聊列表
    socketState.initChatList(chatlist);

    // 设置app红点
    int count = socketState.chatList.fold(0, (preValue, item) {
      return preValue + item.readCount;
    });
    if (count > 0) {
      FlutterAppBadger.updateBadgeCount(count);
    } else {
      FlutterAppBadger.removeBadge();
    }

    return chatlist;
  }

  /// 查询与指定用户私信历史记录
  Future queryDialogue(String targetToken) async {
    List<Map> list = await db.rawQuery(
        "SELECT * FROM $MESSAGE_TABLE_NAME WHERE token = '$targetToken' AND userToken = '${_userInfo.memberToken}'");
    if (list.length > 0) {
      Map<String, dynamic> chat = {
        "token": list?.last['token'],
        "userName": list?.last['userName'],
        "userHead": list?.last['userHead'],
        "msglist": list,
      };
      return ChatModel.fromJson(chat);
    } else {
      return null;
    }
  }

  /// 更新与指定用户私信的已读状态
  updateDialogue(String targetToken) async {
    await db.update(
      '$MESSAGE_TABLE_NAME',
      {'isread': 1},
      where: 'userToken = ? AND token = ?',
      whereArgs: [_userInfo.memberToken, targetToken],
    );
  }

  /// 查询与指定用户的未读私聊总数
  Future queryNotReadCount(String targetToken) async {
    List<Map> list = await db.rawQuery(
        "SELECT * FROM $MESSAGE_TABLE_NAME WHERE token = '$targetToken' AND userToken = '${_userInfo.memberToken}' AND isread = 0");
    return list.length;
  }

  /// 删除与指定用户私信历史记录
  deleteDialogue(String targetToken) async {
    await db.delete(
      '$MESSAGE_TABLE_NAME',
      where: 'userToken = ? AND token = ?',
      whereArgs: [_userInfo.memberToken, targetToken],
    );
  }

  /// 关闭数据库
  close() async {
    queue.dispose();
    queue = null;
    await db?.close();
  }
}
